package com.polaris.live.manager

import android.app.Application
import com.blankj.utilcode.util.StringUtils
import com.google.android.recaptcha.Recaptcha
import com.google.android.recaptcha.RecaptchaClient
import com.polaris.live.R
import com.polaris.live.common.AppModule
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.LogExt
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * GoogleRecaptchaManager
 *
 * @author Created by lucas on 2023/11/22 14:33
 */
object GoogleRecaptchaManager {

    /**
     * GoogleRecaptchaClient
     */
    var recaptchaClient: RecaptchaClient? = null

    fun init(application: Application) {
        initRecaptchaClient(application)
    }

    private fun initRecaptchaClient(application: Application, times: Int = 0) {
        GlobalScope.launch(CoroutineScopeManager.ioDispatcher) {
            try {
                if (!AppModule.checkGoogleServices()) return@launch
                Recaptcha.getClient(application, StringUtils.getString(R.string.google_verify_key))
                    .onSuccess {
                        recaptchaClient = it
                    }
                    .onFailure {
                        if (times < 3) {
                            initRecaptchaClient(application, times + 1)
                        }

                        LogExt.logE("--net", it)
                    }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}